package com.km.wskj.itmonitor.pager.wq.forum;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.login.LoginActivity;
import com.km.wskj.itmonitor.pager.news.NewsDetailActivity;
import com.km.wskj.itmonitor.pager.wq.forum.model.CommentParams;
import com.km.wskj.itmonitor.pager.wq.forum.model.ForumCard;
import com.km.wskj.itmonitor.pager.wq.forum.model.ForumComment;
import com.km.wskj.itmonitor.pager.wq.forum.model.ForumDetail;
import com.km.wskj.itmonitor.pager.wq.forum.model.ForumImg;
import com.km.wskj.itmonitor.pager.wq.note.model.AddCallback;
import com.km.wskj.itmonitor.utils.CustomShareListener;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.model.ImageData;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

/**
 * @author by Xianling.Zhou on 2017/3/30.
 */
//帖子详情页面
public class ForumDetailActivity extends LActivity {
    private static final String TAG = "ForumDetailActivity";

    //ui
    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.tool_bar_right)
    ImageView mShare;
    @BindView(R.id.zrcListView)
    ZrcListView mZrcListView;
    @BindView(R.id.et_comment)
    EditText etComment;
    @BindView(R.id.tv_send_comment)
    TextView tvSendComment;

    TextView tvAuthor;
    TextView tvCreateTime;
    WebView mContent;
    TextView tvTitle;
    LinearLayout containerPics;
    ImageView ivHeader;

    //data
    private ForumCard mForumCard;
    private ForumDetail mForumDetail;
    private MyAdapter mAdapter;
    private int lastUpdateNum;
    private int pageIndex;

    private List<ForumComment> mForumComment;


    private UMShareListener mShareListener;
    private ShareAction mShareAction;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forum_detail);

        ButterKnife.bind(this);
        toolBarBack.setVisibility(View.VISIBLE);
        mShare.setVisibility(View.VISIBLE);
        mShare.setImageResource(R.mipmap.share_white);

        if (getIntent().hasExtra("data")) {
            mForumCard = (ForumCard) getIntent().getSerializableExtra("data");
            toolBarTitle.setText(mForumCard.title + "");
        }

        initPullToRefresh();
        initData();
        onRefresh();
        initShare();
    }

    //初始化分享
    private void initShare() {
        mShareListener = new CustomShareListener(context);
        /*增加自定义按钮的分享面板*/
        mShareAction = new ShareAction(context).setDisplayList(
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE
        )
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        UMWeb web = new UMWeb("http://fir.im/wsipos");
                        web.setTitle("来自IT智慧运维");
                        web.setDescription("让运维变得更美好");
                        web.setThumb(new UMImage(context, R.mipmap.logo));
                        new ShareAction(context).withMedia(web)
                                .setPlatform(share_media)
                                .setCallback(mShareListener)
                                .share();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private void initData() {
        pdc.forumDetail(HTTP_TASK_TAG, mForumCard.id, new ZxlGenericsCallback<ForumDetail>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(ForumDetail forumDetail, int i) {
                mForumDetail = forumDetail;
                refresh();
            }
        });

    }

    private void initPullToRefresh() {
        //添加头布局
        View view = getLayoutInflater().inflate(R.layout.header_forum_detail, null);
        mZrcListView.addHeaderView(view, null, true);//注意：第三个参数必须为true，否则无效

        tvAuthor = (TextView) view.findViewById(R.id.tv_author);

        tvCreateTime = (TextView) view.findViewById(R.id.tv_create_time);
        mContent = (WebView) view.findViewById(R.id.wb_content);
        containerPics = (LinearLayout) view.findViewById(R.id.container_pics);
        ivHeader = (ImageView) view.findViewById(R.id.header_img);
        tvTitle = (TextView) view.findViewById(R.id.tv_title);

        tvAuthor.setText(mForumCard.nickname != null
                ? mForumCard.nickname
                : mForumCard.tel_no.substring(0, 3) + "****" + mForumCard.tel_no.substring(7) + "");
        tvCreateTime.setText(mForumCard.createTime + "");
        mContent.loadDataWithBaseURL(null, mForumCard.content + "", "text/html", "utf-8", null);
        tvTitle.setText(mForumCard.title + "");

        //设置头像
        if (mForumCard.head_img != null) {
            Glide.with(context)
                    .load(mForumCard.host + mForumCard.head_img)
                    .into(ivHeader);
        }

        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#f1f1f1"));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);
//        mZrcListView.setHeaderDividersEnabled(false);


        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });
        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
//                ForumCard fc = (ForumCard) parent.getItemAtPosition(position);
//                Intent t = new Intent(context, ForumDetailActivity.class);
//                t.putExtra("data", fc);
//                startActivity(t);
            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);
    }

    private void onRefresh() {
        pdc.commentList(HTTP_TASK_TAG, 1, Constant.PageListSize, mForumCard.id, new ZxlGenericsCallback<List<ForumComment>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                mZrcListView.setRefreshFail("数据获取失败");
            }

            @Override
            public void onResponse(List<ForumComment> fcs, int i) {
                mForumComment = fcs;
                lastUpdateNum = fcs.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });
    }

    private void onLoadMore() {
        pdc.commentList(HTTP_TASK_TAG, pageIndex + 1, Constant.PageListSize, mForumCard.id, new ZxlGenericsCallback<List<ForumComment>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                mZrcListView.setRefreshFail("数据获取失败");
            }

            @Override
            public void onResponse(List<ForumComment> fcs, int i) {
                lastUpdateNum = fcs.size();
                if (fcs.size() > 0) {
                    mForumComment.addAll(fcs);
                    pageIndex++;
                }
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setLoadMoreSuccess();
                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });
    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    private void refresh() {
        List<ForumImg> imgs = mForumDetail.forumImgs;

        for (int i = 0; i < imgs.size(); i++) {
            ForumImg forumImg = imgs.get(i);
            String imgUrl = forumImg.host + forumImg.filePath + forumImg.newFileName;
            ImageView iv = new ImageView(context);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setAdjustViewBounds(true);

            Glide.with(context).load(imgUrl).into(iv);

            LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//            p.setMargins(20, 20, 20, 0);
            containerPics.addView(iv, p);
        }
    }


    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (mForumComment == null) {
                return 0;
            }
            return mForumComment.size();
        }

        @Override
        public Object getItem(int position) {
            return mForumComment.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView, parent, R.layout.item_comment_list);
            ForumComment item = mForumComment.get(position);
            String tel_no = item.tel_no;
            String tel = null;
            if (tel_no.length() == 11)
                tel = item.tel_no.substring(0, 3) + "****" + item.tel_no.substring(7);

            helper.setText(R.id.tv_author, item.nickname == null ? tel : item.nickname);
            helper.setText(R.id.tv_comment, item.content + "");

            helper.setText(R.id.tv_create_time, item.createTime + "");

            //设置头像
            if (item.head_img != null) {
                Glide.with(context)
                        .load(item.host + item.head_img)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.header_img, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型
            }

            return helper.getView();
        }
    }

    @OnClick({R.id.tool_bar_back, R.id.tv_send_comment, R.id.tool_bar_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tool_bar_back:
                finish();
                break;
            case R.id.tool_bar_right:
                mShareAction.open();
                break;
            case R.id.tv_send_comment:
                String comment = etComment.getText().toString();
                if (comment.equals("")) {
                    normalToasty("评论不能为空");
                    return;
                }
                //当前用户未登录
                if (pdc.mCurrentUser == null) {
                    normalToasty("请先登录");
                    openIntent(LoginActivity.class, true);
                    return;
                }

                CommentParams params = new CommentParams();
                params.userId = pdc.mCurrentUser.userId;
                params.content = comment;
                params.forumId = mForumDetail.forumInfo.id;


                pdc.addComment(HTTP_TASK_TAG, params, new ZxlGenericsCallback<AddCallback>() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        LogUtils.e(TAG, e);
                    }

                    @Override
                    public void onResponse(AddCallback addCallback, int i) {
                        normalToasty("评论成功！");
                        etComment.setText("");
                        //方法一(如果输入法在窗口上已经显示，则隐藏，反之则显示)
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                        onRefresh();
                    }
                });
                break;
        }
    }
}
